﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.DBUtility;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ultimus.WFServer;
using H2.NET.Web.API.Model;

namespace H2.NET.Web.Pages.SMD
{
    public partial class Store : BasePage
    {
        public DataTable area = new DataTable();
        public string IsReapter;
        public string subdealerCallBack { get; set; }
        public string bmcCallBack { get; set; }
        public string accountownerCallBack { get; set; }


        #region 页面加载事件

        protected void Page_Load(object sender, EventArgs e)
        {
            btn_submit.Visible = TaskAPI.IsAllowSubmit;

            #region 选择负责销售 Add By Tony 20160607
            Dictionary<string, string> accountownerDic = new Dictionary<string, string>();

            accountownerDic.Add(tb_accountowner.ClientID, "AccountOwner");
            accountownerDic.Add(h_windowsid.ClientID, "WindowsId");
            uc_search_accountowner1.accountownerDic = accountownerDic;
            uc_search_accountowner1.accountownerCallBack = accountownerCallBack;
            #endregion

            #region 选择建材市场 Add By Tony 20160607
            Dictionary<string, string> bmcDic = new Dictionary<string, string>();

            bmcDic.Add(bmccode.ClientID, "BMCCode");
            bmcDic.Add(l_bmcname.ClientID, "BMCName");
            uc_search_bmc1.bmcDic = bmcDic;
            uc_search_bmc1.bmcCallBack = bmcCallBack;
            #endregion
            


            #region 选择分销商-- Add By Tony 20160601

            if (cb_ownertype.Checked == false)
            {
                subdealercode.Style.Add("Display", "none");
            }
            else
            {
                subdealercode.Style.Add("Display", "inline");
            }

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add(subdealer_id.ClientID, "SubDealerID");
            dic.Add(subdealercode.ClientID, "SubDealerCode");
            dic.Add(l_subdealername.ClientID, "SubDealerName");
            uc_search_subdealer1.dic = dic;
            uc_search_subdealer1.subdealerCallBack = subdealerCallBack;
            #endregion
          

            #region 筛选门店
            if (AksRequest.GetQueryString("action") == "filterStore")
            {
                string province = AksRequest.GetString("province");
                string city = AksRequest.GetString("city");
                string address = AksRequest.GetString("address");
                string result = "";
                if (!string.IsNullOrEmpty(province) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(address))
                {
                    string sql = "SELECT [StoreID] ,[AuthID],[StoreName], [Region], [Province], [cityname],[StoreAddress], [ContactPerson], [StoreStatus], [StoreType] ,dbo.semblance('" + address + "', StoreAddress) as 相似度" +
                                " FROM [t_smd_Store] " +
                                "where Province='" + province + "' and cityname='" + city + "' and dbo.semblance('" + address + "', StoreAddress)>20 ";
                    DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
                    DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var rst = "";
                            rst += dt.Rows[i]["AuthID"] + ",";
                            rst += dt.Rows[i]["StoreName"] + ",";
                            rst += dt.Rows[i]["Region"] + ",";
                            rst += dt.Rows[i]["Province"] + ",";
                            rst += dt.Rows[i]["cityname"] + ",";
                            rst += dt.Rows[i]["StoreAddress"] + ",";
                            rst += dt.Rows[i]["ContactPerson"] + ",";
                            rst += dt.Rows[i]["StoreStatus"] + ",";
                            rst += dt.Rows[i]["StoreType"] + ",";
                            rst += dt.Rows[i]["相似度"];
                            result += rst + "|";
                        }
                    }
                }
                SuccessMsg(result);
                return;
            }
            #endregion
            

            #region 筛选省份和城市
            else if (AksRequest.GetQueryString("action") == "initProvince")
            {
                var type = AksRequest.GetFormString("type");
                var ar = AksRequest.GetFormString("ar");
                var and = string.Empty;
                if (AksRequest.GetFormString("type") == "province")
                {
                    and = " and [level] = 2 ";
                }
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
                DataTable province = DbHelperSQL.Query("select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" + ar + "' " + and + ") order by seq asc").Tables[0];
                var result = "";
                if (province.Rows.Count > 0)
                {
                    for (int i = 0; i < province.Rows.Count; i++)
                    {
                        var rst = "";
                        rst += province.Rows[i]["Value"] + ",";
                        rst += province.Rows[i]["Name"] + ",";
                        result += rst + "|";
                    }
                }
                SuccessMsg(result);
                return;
            }
            #endregion

            #region switchNewFitment
            else if (AksRequest.GetQueryString("action") == "switchNewFitment")
            {
                string fitmentType = AksRequest.GetFormString("fitmentType");
                if (fitmentType.Equals("全新门店"))
                {
                    SuccessMsg("1");
                }
                SuccessMsg("2");
                return;
            }
            #endregion

            if (!Page.IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    btn_submit.Visible = false;
                    return;
                }

                InitDropDownList();

                #region 发起步骤
                if (TaskAPI.IsInitiate)
                {
                    uc_head1.summary = "仅针对E-approve审批以外需要额外添加的门店登记使用（添加需要DR2邮件审批）";

                    uc_dealer1.isShowShortName = true;
                    uc_dealer1.isCanChoose = true;
                    uc_dealer1.dealerCallBack = "dealerCallBack";

                    td_ShopSeq.Attributes.Add("colspan", "3");
                    td_isDevice.Attributes.Add("colspan", "5");
                    th_ApplactionType.Visible = false;
                    td_ApplactionType.Visible = false;
                    th_MachineDeposit.Visible = false;
                    td_MachineDeposit.Visible = false;
                    th_NewFitment.Visible = false;
                    td_NewFitment.Visible = false;
                }
                #endregion

                #region 审批环节
                else
                {
                    var store = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);

                    if (store == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }

                    uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                    uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                    uc_head1.date = store.SubmitDate.Value.ToString("yyyy-MM-dd");
                    uc_head1.isEapprove = store.IsEapprove == true;

                    assessment.Visible = true;
                    var storez = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);//chris wang
                    t_smd_Dealer dealer1 = DealerService.GetByCode(storez.DealerCode);
                    uc_dealer1.dealer = dealer1;
                    //if ((storez.NewFitment.IndexOf("全新门店") > -1) || ((storez.NewFitment.IndexOf("仅调色机申请") > -1) && ((storez.StoreType.IndexOf("MT") > -1) || (storez.StoreType.IndexOf("LCSS") > -1) || (storez.StoreType.IndexOf("HDC") > -1) || (storez.StoreType.IndexOf("LIS") > -1) || (storez.StoreType.IndexOf("EPS") > -1) || (storez.StoreType.IndexOf("E-COMMERCE") > -1))))
                    if ((storez.NewFitment.IndexOf("全新门店") > -1) || ((storez.NewFitment.IndexOf("仅调色机申请") > -1) && ((storez.StoreType.IndexOf("DDCN") == -1) || (storez.StoreType.IndexOf("DCSS") == -1) )))
                    {
                        uc_dealer1.FirstShowDealer(dealer1.DealerCode);//chris wang
                        uc_dealer1.IsCanEditAuthID = false;
                    }
                    else
                    {
                        t_smd_Store st = StoreService.GetSmdStoreByAuthID(storez.AuthID);
                        uc_dealer1.store = st;
                        uc_dealer1.quanxindealer = false;
                    }
                    uc_dealer1.IsReadonly = true;
                    //uc_dealer1.IsShortName = store.DealerShortName;
                    //uc_dealer1.IsReadonly = true;
                    //uc_dealer1.IsCanEditAuthID = false;

                    // 经销商数据
                    t_smd_Dealer dealer = DealerService.GetByCode(store.DealerCode);
                    uc_dealer1.dealer = dealer;
                    tr_authId.Style.Value = "display:''";


                    //分销商信息
                    if (!string.IsNullOrEmpty(store.SubDealerCode))
                    {
                        t_smd_Dealer subdealer = DealerService.GetByCode(store.SubDealerCode);
                        if (subdealer != null)
                        {
                            cb_ownertype.Checked = true;
                            l_subdealercode.Text = subdealer.DealerCode;
                            l_subdealername.Text = subdealer.Name;
                        }
                        else
                        {
                            cb_ownertype.Checked = false;
                            l_subdealercode.Text = "";
                            l_subdealername.Text = "";
                        }
                    }
                    else
                    {
                        cb_ownertype.Checked = false;
                        l_subdealercode.Text = "";
                        l_subdealername.Text = "";
                    }


                    #region 审批项初始化
                    switch (TaskAPI.Step)
                    {
                        case "Assign AuthID":
                            // 从数据库中查出已用授权号，并根据规则给出建议号码
                            if (string.IsNullOrEmpty(store.AuthID) || !StoreService.IsExistAuthID(store.AuthID))
                            {
                                var storeTypeCode = StoreService.GetStoreTypeCode(store.StoreType);
                                tb_authID.Text = AuthIDService.GetNextNumber(store.ProvinceName, storeTypeCode, true);
                                hf_authID.Value = tb_authID.Text;
                            }
                            else
                            {
                                tb_authID.Text = store.AuthID;
                            }
                            cb_cover.Visible = true;
                            checkAuthID.Visible = true;
                            ShowData(store);

                            //Logging.GetLogger().Error("节点1");
                            // 判断授权号是否重复，（IsEapprove 提示文本的区分）
                            if (store.IsEapprove == false && StoreService.GetSmdStoreByAuthID(store.AuthID).StoreID > 0)
                            {
                                IsReapter = "1";
                            }
                            //Logging.GetLogger().Error("节点2");
                            break;
                        case "AuthID Confirm":
                        case "CSM Confirm":
                            tb_authID.Attributes.Add("readonly", "readonly");
                            tb_authID.Text = store.AuthID;
                            if (store.NewFitment == "全新门店")
                            {
                                cb_isRepeat.Visible = true;
                            }

                            ShowData(store);
                            break;
                    }
                    #endregion

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;
                }

                #endregion

                SetVisible(TaskAPI.IsAllowSubmit, btn_submit);
            }
        }

        #endregion

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);
                uc_dealer1.IsReadonly = true;
                var storez = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);//chris wang
                t_smd_Dealer dealer1 = DealerService.GetByCode(storez.DealerCode);
                uc_dealer1.dealer = dealer1;

                //if (storez.NewFitment.IndexOf("全新门店") > -1)
                if ((storez.NewFitment.IndexOf("全新门店") > -1) || ((storez.NewFitment.IndexOf("仅调色机申请") > -1) && ((storez.StoreType.IndexOf("DDCN") == -1) || (storez.StoreType.IndexOf("DCSS") == -1))))
                {
                    uc_dealer1.FirstShowDealer(dealer1.DealerCode);//chris wang
                    uc_dealer1.IsCanEditAuthID = false;
                }
                else
                {
                    //Logging.GetLogger().Error("测试节点3");
                    t_smd_Store st = StoreService.GetSmdStoreByAuthID(storez.AuthID);
                    //Logging.GetLogger().Error("测试节点4");
                    uc_dealer1.store = st;
                    uc_dealer1.quanxindealer = false;
                }
                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var store = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                if (store == null)
                {
                    hideController();
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                var dealer = DealerService.GetByCode(store.DealerCode);
                uc_dealer1.dealer = dealer;

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = store.SubmitDate.Value.ToString("yyyy-MM-dd");
                uc_head1.isEapprove = store.IsEapprove == true;

                ShowData(store);

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        #region 数据处理方法

        private bool Send(ref string msg)
        {

            bool flag = false;
            try
            {
                var model = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);

                #region 数据验证
                if (TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit)
                {
                    var eapproveSn = tb_EapproveSN.Text;
                    var deviceEapproveSn = tb_DeviceEapproveSN.Text;
                    if (!string.IsNullOrEmpty(eapproveSn))
                    {
                        if (StoreService.IsExistSn(eapproveSn))
                        {
                            msg = "门店系统流水号已存在！";
                            return false;
                        }
                    }

                    if (!string.IsNullOrEmpty(deviceEapproveSn))
                    {
                        if (StoreService.IsExistSn(deviceEapproveSn))
                        {
                            msg = "设备系统流水号已存在！";
                            return false;
                        }
                    }

                    if (cb_ShowInWebsite.Checked && !ajaxUpload1.IsHaveAttachment)
                    {
                        msg = "请提交DR2审批邮件！";
                        return false;
                    }
                }
                else if (TaskAPI.Step == "Assign AuthID" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    // 完成选项，需要处理主数据才进行验证
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        if (model.IsEapprove == true && string.IsNullOrEmpty(model.Status))
                        {
                            //model.Status = "E-approve导入无状态";
                            model.Status = "CRM导入无状态";
                        }

                        if (string.IsNullOrEmpty(tb_authID.Text))
                        {
                            msg = "对不起，授权号不能为空！";
                            return false;
                        }
                        if (string.IsNullOrEmpty(model.StoreName))
                        {
                            msg = "对不起，门店名称不能为空！";
                            return false;
                        }
                        if (string.IsNullOrEmpty(model.Status))
                        {
                            msg = "对不起，门店状态不能为空！";
                            return false;
                        }
                        if (string.IsNullOrEmpty(model.StoreType))
                        {
                            msg = "对不起，门店类型不能为空！";
                            return false;
                        }

                        if (cb_cover.Checked && !StoreService.IsExistAuthID(tb_authID.Text))
                        {
                            msg = "对不起，您选择了覆盖，但是在门店主数据库并未找到该授权号的门店信息！";
                            return false;
                        }
                    }
                }
                else if (TaskAPI.Step == "AuthID Confirm" || TaskAPI.Step == "CSM Confirm" && TaskAPI.IsAllowSubmit)
                {
                    if (cb_isRepeat.Checked && !StoreService.IsExistAuthID(tb_authID_Has.Text))
                    {
                        msg = "对不起，授权号不存在！";
                        return false;
                    }
                }
                else if (TaskAPI.Step == "CSM Confirm" && TaskAPI.IsAllowSubmit)
                {
                    if (DwzAssessment1.Assessment.Remark == "")
                    {
                        msg = "请填写备注，授权号可能需要您确认，谢谢。";
                        return false;
                    }
                }

                if (TaskAPI.Step == "AuthID Confirm" || TaskAPI.Step == "CSM Confirm")
                {
                    if (DwzAssessment1.Assessment.Remark == "" && DwzAssessment1.Assessment.Opinion == "2")
                    {
                        msg = "请填写驳回原因，谢谢";
                        return false;
                    }
                }

                #endregion

                #region 引擎传值

                #region 如果是第一步--Fill the request
                if (TaskAPI.IsBeginStep)
                {
                    if (TaskAPI.IsInitiate)
                    {
                        TaskAPI.InitTask(UserAPI, uc_head1.applicationNo);
                    }

                    TaskAPI.Summary = "发放授权号/门店-" + AksRequest.GetString("tb_store_name") + "|" + uc_dealer1.code;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI["AutoBusinessKey"] = Constant.PROCESS_STORE;
                    TaskAPI["IsEapprove"] = "非E-approve发起";
                    TaskAPI.SetNewStoreApplicationRecipient(
                        AksRequest.GetString("tb_region").Trim().ToUpper(),
                        AksRequest.GetString("tb_province").Trim());

                    #region 邮件相关变量

                    TaskAPI["StoreName"] = AksRequest.GetString("tb_store_name");
                    TaskAPI["StoreType"] = store_type.SelectedItem.Text;
                    TaskAPI["StoreAddress"] = AksRequest.GetString("tb_address");
                    TaskAPI["IsDevice"] = cb_isDevice.Checked ? 1 : 0;

                    #endregion
                }
                #endregion

                #region 其他情况
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;

                    if (TaskAPI.Step == "Assign AuthID")
                    {
                        TaskAPI["IsChannelManagerConfirm"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "发放授权号/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code;
                        }

                        #region 邮件相关变量
                        TaskAPI["AuthIDApply"] = tb_authID.Text;
                        TaskAPI["AuthIDConfirmed"] = tb_authID.Text;
                        TaskAPI["StoreName"] = model.StoreName;
                        TaskAPI["StoreAddress"] = model.Address;
                        #endregion
                    }
                    else if (TaskAPI.Step == "AuthID Confirm" || TaskAPI.Step == "CSM Confirm")
                    {
                        TaskAPI.Summary = "授权号确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code;

                        #region 邮件相关变量
                        TaskAPI["StoreName"] = tb_store_name.Text;
                        TaskAPI["StoreType"] = store_type.SelectedItem.Text;
                        TaskAPI["StoreAddress"] = tb_address.Text;
                        TaskAPI["IsDevice"] = cb_isDevice.Checked ? 1 : 0;
                        if (model.IsEapprove == true)
                        {
                            TaskAPI["SerialNumber"] = tb_EapproveSN.Text;
                        }

                        if (cb_isRepeat.Checked)
                        {
                            TaskAPI["AuthIDConfirmed"] = tb_authID_Has.Text;
                        }
                        else
                        {
                            TaskAPI["AuthIDConfirmed"] = tb_authID.Text;
                        }
                        TaskAPI["AuthIDConfirmer"] = UserAPI.UserFullName;

                        TaskAPI["Confirmed"] = "1";
                        TaskAPI["CSM_Confirmed"] = "1";
                        #endregion
                    }
                }
                #endregion

                #endregion

                #region 提交步骤

                string step = string.Empty;

                int storeid = 0;
                int deviceid = 0;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    var ass = DwzAssessment1.Assessment;

                    if (cb_isRepeat.Checked && (TaskAPI.Step == "AuthID Confirm" || TaskAPI.Step == "CSM Confirm"))
                    {
                        ass.Remark = "原授权号：" + tb_authID.Text + "，新授权号：" + tb_authID_Has.Text + "。" + ass.Remark;
                    }

                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Fill in the form”步骤
                    if (TaskAPI.IsBeginStep)
                    {
                        var store = FormatStoreMasterData();
                        Storage.Save(Storage.Context1, store);
                    }
                    #endregion

                    #region “Assign AuthID”步骤
                    if (TaskAPI.Step == "Assign AuthID")
                    {
                        model.AuthID = tb_authID.Text;

                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            var store = new t_smd_Store();
                            var device = new t_smd_Device();
                            List<SmdSync> syncList = new List<SmdSync>();
                            StoreService.SaveStore(model, ref store, ref device, cb_cover.Checked);
                            StoreService.SaveDealerShort(store.StoreID);
                            //store.DealerShortName = syncmodel.DealershortName;
                            Boolean isNew = false;

                            // 如果门店信息已存在，就覆盖原有的数据
                            var smd_store = StoreService.GetSmdStoreByAuthID(store.AuthID);
                            if (smd_store.StoreID == 0)
                            {
                                isNew = true;
                                smd_store.AuthID = store.AuthID;
                                smd_store.StoreName = store.StoreName;

                                Storage.Save(Storage.Context3, smd_store);
                            }

                            if (smd_store.StoreID > 0)
                            {
                                store.StoreID = smd_store.StoreID;
                                store.EntityState._FieldState.Remove("StoreID");
                                store.EntityState._Loaded = true;
                            }
                            if (cb_cover.Checked || isNew)
                            {
                                var storeChangelogs = DataHelper<t_smd_Store>.GetChangeLogs(smd_store, store,
                                    store.GetChangeFields(), "StoreID", UserAPI.UserFullName, ass.ID, "NewStoreChangeLog");
                                var smd_changelogs = ChangeLogService.McdToSmd(storeChangelogs);
                                Storage.Save(Storage.Context3, smd_changelogs.ToArray());
                                Storage.Save(storeChangelogs.ToArray());

                                Storage.Save(Storage.Context3, store);
                            }


                            #region 如果和隐藏域相同的值，说明是自动生成的序列号
                            if (hf_authID.Value.Trim().ToUpper() == tb_authID.Text.Trim().ToUpper())
                            {
                                if (model.NewFitment == "从IS升级")
                                {
                                    AuthIDService.GetNextNumber(model.ProvinceName, StoreService.GetStoreTypeCode("DCSS"), false);
                                }
                                else if (model.NewFitment == "从DCSS升级")
                                {
                                    AuthIDService.GetNextNumber(model.ProvinceName,
                                        StoreService.GetStoreTypeCode("DDCN"), false);
                                }
                                else
                                {
                                    AuthIDService.GetNextNumber(model.ProvinceName,
                                        StoreService.GetStoreTypeCode(model.StoreType), false);
                                }

                            }
                            #endregion

                            #region 如果是手动添加的，需要处理设备主数据。否则放到 storemasterdata 中，带入到下个流程（保证金收取）处理
                            if (model.IsEapprove == false)
                            {
                                // 如果设备已存在，就覆盖原有的数据
                                if (StoreMasterDataService.IsExistDevice(model) && cb_cover.Checked)
                                {
                                    if (device.DeviceID > 0)
                                    {
                                        device.EntityState._FieldState.Remove("DeviceID");
                                        device.EntityState._Loaded = true;
                                    }
                                }
                                var smdDevice = DeviceService.GetSmdDeviceByFullSetSN(model.DeviceFullSetSN);
                                device.StoreID = store.StoreID;
                                Storage.Save(Storage.Context3, device);

                                var deviceChangelogs = DataHelper<t_smd_Device>.GetChangeLogs(smdDevice, device,
                                        device.GetChangeFields(), "DeviceID", UserAPI.UserFullName, ass.ID, "ChangeDevice");
                                Storage.Save(Storage.Context3, deviceChangelogs.ToArray());
                            }
                            #endregion



                            model.StoreId = storeid = store.StoreID;
                            model.DeviceId = deviceid = device.DeviceID;
                            model.Step = step = "Finish";

                            TaskAPI["BlankVlue"] = store.StoreID;
                            if (!TaskHelper.getSummary(TaskAPI.Summary).Contains("NS"))
                            {
                                TaskAPI.Summary = "发放授权号/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + "|" + uc_dealer1.code;
                            }
                        }
                        else
                        {
                            step = model.Step = "AuthID Confirm";

                        }

                        Storage.Save(model);
                    }
                    #endregion

                    #region “AuthID Confirm”，“CSM Confirm”步骤

                    else if (TaskAPI.Step == "AuthID Confirm" || TaskAPI.Step == "CSM Confirm")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            // 更新数据
                            //model = FormatStoreMasterData(model);

                            // 如果有重复门店，则取新填写的授权号
                            if (cb_isRepeat.Checked)
                            {
                                model.AuthID = tb_authID_Has.Text;
                            }

                            Storage.Save(model);
                            if (!TaskHelper.getSummary(TaskAPI.Summary).Contains("NS"))
                            {
                                TaskAPI.Summary = "授权号确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + "|" + uc_dealer1.code;
                            }
                        }
                    }

                    #endregion
                });

                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    flag = TaskAPI.Send();
                }

                #region 更新实例号

                if (TaskAPI.IsInitiate)
                {
                    (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == 0).Edit<t_StoreMasterData>(p =>
                    {
                        p.Step = "Assign AuthID";
                        p.Incident = TaskAPI.Incident;
                        Task task = TaskHelper.GetTask(TaskAPI.Process, TaskAPI.Incident, "Assign AuthID");
                        p.TaskId = task.strTaskId;
                    });
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }

                #endregion

                #region 自动发起流程

                if (step == "Finish" && flag)
                {

                    BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                    var store = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                    var smdStore = StoreService.GetSmdStoreById(store.StoreId.Value);
                    var dealer = DealerService.GetByCode(store.DealerCode);
                    //var devicer = DeviceService.GetOneByStoreId(store.StoreId.Value);
                    //var deposit = DepositService.GetDepositByStoreId(store.StoreId.Value);
                    BusinessService.saveProcessRelation(TaskAPI, DwzAssessment1.Assessment, smdStore, null, dealer, null, null, null, null);

                    #region Add By Tony 20160530
                    t_smd_Dealer subdealer = new t_smd_Dealer();
                    if (!string.IsNullOrEmpty(store.SubDealerCode))
                    {
                        subdealer = DealerService.GetByCode(store.SubDealerCode);
                    }

                    //BusinessService.SaveCRMSyncData(store, smdStore, dealer, devicer, deposit, subdealer);
                    //BusinessService.SaveCRMSyncData(store, smdStore, dealer, subdealer);

                    #endregion


                    if (store.IsEapprove == false)
                    {
                        #region 自动启动门店信息变更
                        TaskAPI taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                        string applicationNo = GenerateApplicationNo(taskAPI);

                        taskAPI["AutoBusinessKey"] = Constant.PROCESS_STORE;
                        taskAPI["ParentProcess"] = TaskAPI.Process;
                        taskAPI["ParentIncident"] = TaskAPI.Incident;
                        taskAPI["BlankVlue"] = store.StoreId;
                        taskAPI["Actions"] = "ChangeStore";
                        if (cb_isDevice.Checked)
                        {
                            taskAPI["DeviceID"] = store.DeviceId;
                        }
                        taskAPI.InitAutoTask(applicationNo);
                        taskAPI.Summary = "提交基础信息变更/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                        taskAPI["Region"] = store.AreaName;
                        taskAPI["Province"] = store.ProvinceName;
                        taskAPI["Category"] = "Store";
                        taskAPI.SetStoreDataChangeRecipient(store.AreaName, store.ProvinceName, "Store");

                        if (taskAPI.Send())
                        {
                            var ass = taskAPI.InitAutoAssessment();
                            Storage.Save(Storage.Context1, ass);
                            BusinessService.SaveChildProcess(taskAPI, ass, "active");
                        }

                        #endregion
                    }
                    else
                    {
                        #region 启动收取保证金流程

                        //var taskApi = new TaskAPI(TaskHelper.STORE_DEPOSIT_RECEIVE_TASKID);
                        var taskApi = new TaskAPI(TaskHelper.NEW_STORE_DEPOSIT_RECEIVE_TASKID);
                        var applicationNo = GenerateApplicationNo(taskApi);
                        taskApi["IsRenovation"] = "1";
                        taskApi["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue");
                        taskApi["ParentProcess"] = TaskAPI.Process;
                        taskApi["ParentIncident"] = TaskAPI.Incident;
                        taskApi["AutoBusinessKey"] = Constant.PROCESS_STORE;
                        taskApi.InitAutoTask(applicationNo);
                        taskApi["StoreName"] = smdStore.StoreName;

                        string Summary = string.Empty;

                        //截取类型
                        string type = store.EapproveSN.Substring(0, 3);

                        taskApi["IsCancel"] = "0";

                        if (store.NewFitment.Contains("全新门店") || store.NewFitment.Contains("升级") || store.NewFitment.Contains("翻新"))
                        {
                            if (store.ApplicationType == null || store.ApplicationType.Contains("无需机器"))
                            {
                                //发起履约
                                taskApi["IsMargin"] = "1";
                                Summary = "[履约保证金]上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                                taskApi["IsFinance"] = "1";
                            }
                            else
                            {
                                //yanxiang 17/09/05	当门店升级流程发起时，如果该门店之前已经拥有调色机，CRM给SMD的JSON file中是包括门店基本信息和原有设备信息的，SMD现在会认为是该升级申请同时还有一台新设备申请。
                                //处理意见：由于CRM发到SMD的报文是同时含门店和设备信息，因此SMD中需要判断该设备为新设备还是老设备。如果是老设备就不需要在SMD触发保证金流程
                                if (SmdSyncService.GetTinTingcountBySerialNumber(store.SerialNumber) > 0)
                                {
                                    //发起履约
                                    taskApi["IsMargin"] = "1";
                                    Summary = "[履约保证金]上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                                    taskApi["IsFinance"] = "1";
                                }
                                else
                                {
                                    //发起履约+设备
                                    taskApi["DeviceEapproveSN"] = store.DeviceEapproveSN;
                                    taskApi["BuyMachineDeposit"] = store.BuyMachineDeposit;
                                    taskApi["SerialNumber"] = store.DeviceEapproveSN;
                                    if (store.ApplicationType.Contains("旧机转让") || store.ApplicationType.Contains("MT自动机转移") || store.ApplicationType.Contains("MT手动机转移"))
                                    {
                                        taskApi["IsCancel"] = "1";
                                    }
                                    taskApi["IsDevice"] = "1";
                                    taskApi["IsMargin"] = "1";
                                    Summary = "[设备保证金-履约保证金]上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                                    taskApi["Deposit"] = (store.MachineDeposit ?? 0).ToString();
                                }
                            }
                        }
                        if (store.NewFitment.Contains("仅调色机申请"))
                        {
                            taskApi["OnlyDispense"] = "1";
                            taskApi["IsRenovation"] = "0";
                            if (!store.ApplicationType.Contains("无需机器"))
                            {
                                //发起设备
                                taskApi["IsFinance"] = "1";
                                taskApi["DeviceEapproveSN"] = store.DeviceEapproveSN;
                                taskApi["BuyMachineDeposit"] = store.BuyMachineDeposit;
                                taskApi["SerialNumber"] = store.DeviceEapproveSN;
                                if (store.ApplicationType.Contains("旧机转让") || store.ApplicationType.Contains("MT自动机转移") || store.ApplicationType.Contains("MT手动机转移"))
                                {
                                    taskApi["IsCancel"] = "1";
                                }
                                taskApi["IsDevice"] = "1";

                                Summary = "[上传设备保证金]汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                                taskApi["Deposit"] = (store.MachineDeposit ?? 0).ToString();

                            }
                        }

                        #region
                        //if (string.IsNullOrWhiteSpace(Summary))
                        //{
                        //    Summary = "[履约保证金]上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;

                        //}
                        //taskApi["IsCancel"] = "0";
                        ////taskApi["IsDevice"] = "0";
                        //taskApi["IsMargin"] = "1";

                        //if (store.NewFitment == "仅调色机申请")
                        //{
                        //    taskApi["OnlyDispense"] = "1";
                        //    taskApi["IsRenovation"] = "0";
                        //}

                        //if (l_isDevice.Text == @"是")
                        //{
                        //    taskApi["DeviceEapproveSN"] = store.DeviceEapproveSN;
                        //    taskApi["BuyMachineDeposit"] = store.BuyMachineDeposit;
                        //    taskApi["SerialNumber"] = store.DeviceEapproveSN;
                        //    if (store.ApplicationType.Contains("旧机转让") || store.ApplicationType.Contains("MT自动机转移") || store.ApplicationType.Contains("MT手动机转移"))
                        //    {
                        //        taskApi["IsCancel"] = "1";
                        //    }
                        //    taskApi["IsDevice"] = "1";
                        //    Summary = "[保证金-履约保证金]上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                        //    taskApi["Deposit"] = (store.MachineDeposit ?? 0).ToString();
                        //}
                        //else
                        //{
                        //    taskApi["IsFinance"] = "1"; //用于标识只有履约保证金
                        //}
                        #endregion

                        taskApi.Summary = Summary;

                        var channel = store.Channel == "多乐士" ? "DULUX" : "LEVIS";
                        taskApi["DealerID"] = uc_dealer1.dealer.DealerCode;
                        taskApi["AuthID"] = store.AuthID;
                        taskApi["StoreType"] = (store.NewFitment == "从IS升级" ? "DCSS" : store.StoreType);
                        taskApi["Channel"] = channel;

                        taskApi.SetDepositReceiveRecipient(store.AreaName, store.ProvinceName, channel.ToUpper());

                        if (taskApi.Send())
                        {
                            var ass = taskApi.InitAutoAssessment();
                            Storage.Save(Storage.Context1, ass);

                            // 添加业务主数据
                            var _storeMasterData = new t_StoreMasterData();
                            _storeMasterData.SubmitDate = DateTime.Now;
                            _storeMasterData.Creator = taskApi.UserName;
                            _storeMasterData.ApplicationNO = taskApi.ApplicationNo;
                            _storeMasterData.Process = taskApi.Process;
                            _storeMasterData.Incident = taskApi.Incident;
                            _storeMasterData.StoreId = Utils.StrToInt(TaskAPI.GetVariableBySingleValue("BlankVlue"), 0);
                            _storeMasterData.BuyMachineDeposit = store.BuyMachineDeposit;
                            _storeMasterData.DispenseModel = store.DispenseModel;
                            _storeMasterData.ShakerModel = store.ShakerModel;
                            _storeMasterData.PcModel = store.PcModel;
                            _storeMasterData.MachineDeposit = store.MachineDeposit;
                            _storeMasterData.IsEapprove = store.IsEapprove;
                            _storeMasterData.NewFitment = store.NewFitment;
                            _storeMasterData.ApplicationType = store.ApplicationType;
                            _storeMasterData.BusinessKey = ass.BusinessKey;
                            _storeMasterData.BusinessProcess = ass.BusinessProcess;
                            _storeMasterData.DeviceApprovedDate = store.StoreApprovedDate;

                            Storage.Save(Storage.Context1, _storeMasterData);
                            BusinessService.SaveChildProcess(taskApi, ass, "active");
                        }

                        #endregion

                        #region 启动收取保证金流程 -履约保证金

                        //var taskApi = new TaskAPI(TaskHelper.STORE_DEPOSIT_RECEIVE_TASKID);
                        //var applicationNo = GenerateApplicationNo(taskApi);
                        //taskApi["IsRenovation"] = "1";
                        //taskApi["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue");
                        //taskApi["ParentProcess"] = TaskAPI.Process;
                        //taskApi["ParentIncident"] = TaskAPI.Incident;
                        //taskApi["AutoBusinessKey"] = Constant.PROCESS_STORE;
                        //taskApi.InitAutoTask(applicationNo);
                        //taskApi["StoreName"] = smdStore.StoreName;

                        //if (store.NewFitment == "仅调色机申请")
                        //{
                        //    taskApi["OnlyDispense"] = "1";
                        //    taskApi["IsRenovation"] = "0";
                        //}

                        //if (l_isDevice.Text == @"是")
                        //{
                        //    taskApi["DeviceEapproveSN"] = store.DeviceEapproveSN;
                        //    taskApi["BuyMachineDeposit"] = store.BuyMachineDeposit;
                        //    taskApi["SerialNumber"] = store.DeviceEapproveSN;
                        //    if (store.ApplicationType.Contains("旧机转让") || store.ApplicationType.Contains("MT自动机转移") || store.ApplicationType.Contains("MT手动机转移"))
                        //    {
                        //        taskApi["IsCancel"] = "1";
                        //    }
                        //    taskApi["IsDevice"] = "1";
                        //    taskApi.Summary = "上传汇款底单/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                        //    taskApi["Deposit"] = (store.MachineDeposit ?? 0).ToString();

                        //    //else
                        //    //{
                        //    //    taskApi["IsCancel"] = "0";
                        //    //    taskApi["IsDevice"] = "0";
                        //    //    taskApi.Summary = "履约保证金确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;
                        //    //}

                        //    var channel = store.Channel == "多乐士" ? "DULUX" : "LEVIS";
                        //    taskApi["DealerID"] = uc_dealer1.dealer.DealerCode;
                        //    taskApi["AuthID"] = store.AuthID;
                        //    taskApi["StoreType"] = (store.NewFitment == "从IS升级" ? "DCSS" : store.StoreType);
                        //    taskApi["Channel"] = channel;

                        //    taskApi.SetDepositReceiveRecipient(store.AreaName, store.ProvinceName, channel.ToUpper());

                        //    if (taskApi.Send())
                        //    {
                        //        var ass = taskApi.InitAutoAssessment();
                        //        Storage.Save(Storage.Context1, ass);

                        //        // 添加业务主数据
                        //        var _storeMasterData = new t_StoreMasterData();
                        //        _storeMasterData.SubmitDate = DateTime.Now;
                        //        _storeMasterData.Creator = taskApi.UserName;
                        //        _storeMasterData.ApplicationNO = taskApi.ApplicationNo;
                        //        _storeMasterData.Process = taskApi.Process;
                        //        _storeMasterData.Incident = taskApi.Incident;
                        //        _storeMasterData.StoreId = Utils.StrToInt(TaskAPI.GetVariableBySingleValue("BlankVlue"), 0);
                        //        _storeMasterData.BuyMachineDeposit = store.BuyMachineDeposit;
                        //        _storeMasterData.DispenseModel = store.DispenseModel;
                        //        _storeMasterData.ShakerModel = store.ShakerModel;
                        //        _storeMasterData.PcModel = store.PcModel;
                        //        _storeMasterData.MachineDeposit = store.MachineDeposit;
                        //        _storeMasterData.IsEapprove = store.IsEapprove;
                        //        _storeMasterData.NewFitment = store.NewFitment;
                        //        _storeMasterData.ApplicationType = store.ApplicationType;
                        //        _storeMasterData.BusinessKey = ass.BusinessKey;
                        //        _storeMasterData.BusinessProcess = ass.BusinessProcess;
                        //        _storeMasterData.DeviceApprovedDate = store.StoreApprovedDate;

                        //        Storage.Save(Storage.Context1, _storeMasterData);
                        //        BusinessService.SaveChildProcess(taskApi, ass, "active");
                        //    }
                        //}

                        //#region 启动履约保证金流程

                        //Margin(store, smdStore);

                        //#endregion

                        #endregion

                    }
                }
                #endregion

                #endregion

            }
            catch (Exception ex)
            {
                msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用Store.aspx方法Send_Click出错：" + ex);
                flag = false;
            }

            return flag;
        }

        #endregion

        #region 提交按钮事件
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            var msg = string.Empty;
            if (Send(ref msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
            }
            else
            {
                msg = string.IsNullOrEmpty(msg) ? Resources.Global.C_00_Failed : msg;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + msg + "','提示', 'info');", true);
            }
        }
        #endregion

        #region 绑定各选项
        private void InitDropDownList()
        {
            ConfigService configService = new ConfigService();

            #region 门店类型
            DataTable dt_area = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_MDLX') order by seq").Tables[0];
            store_type.AppendDataBoundItems = true;
            store_type.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_area.Rows)
            {
                store_type.Items.Add(new ListItem(row["Name"].ToString(), row["Value"].ToString()));
            }
            #endregion

            #region 门店状态
            DataTable dt_storeStatus = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_MDZT') order by seq").Tables[0];
            ddl_storeStatus.AppendDataBoundItems = true;
            ddl_storeStatus.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_storeStatus.Rows)
            {
                ddl_storeStatus.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 设备信息



            #region 调色机型号
            DataTable dt_dispenseModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_TSJLX') order by seq").Tables[0];
            ddl_dispenseModel.AppendDataBoundItems = true;
            foreach (DataRow row in dt_dispenseModel.Rows)
            {
                ddl_dispenseModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 震荡机型号
            DataTable dt_shakerModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_ZDJLX') order by seq").Tables[0];
            ddl_shakerModel.AppendDataBoundItems = true;
            foreach (DataRow row in dt_shakerModel.Rows)
            {
                ddl_shakerModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 电脑型号
            DataTable dt_PcModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DNXH') order by seq").Tables[0];
            ddl_PcModel.AppendDataBoundItems = true;
            foreach (DataRow row in dt_PcModel.Rows)
            {
                ddl_PcModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #endregion

            #region 渠道
            DataTable dt_channel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_QD') order by seq").Tables[0];
            ddl_channel.AppendDataBoundItems = true;
            ddl_channel.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_channel.Rows)
            {
                ddl_channel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 店序号
            ddl_ShopSeq.AppendDataBoundItems = true;
            ddl_ShopSeq.Items.Add(new ListItem("无", ""));
            for (int i = 1; i < 11; i++)
            {
                ddl_ShopSeq.Items.Add(new ListItem(i + "店", i + "店"));
            }
            #endregion
        }
        #endregion

        #region “Fill in the Form”保存业务数据
        private t_StoreMasterData FormatStoreMasterData(t_StoreMasterData store = null)
        {
            string applicationNo = uc_head1.applicationNo;

            #region Add By Tony 20160629

            var accountOwner = new t_smd_AccountOwner();
            if (!string.IsNullOrEmpty(tb_accountowner.Text))
            {
                accountOwner = AccountOwnerService.GetById(tb_accountowner.Text);
            }

            var bmc = new t_smd_BMCInfo();
            if (!string.IsNullOrEmpty(bmccode.Text))
            {
                bmc = BMCService.GetByCode(bmccode.Text);
            }


            var subdealer = new t_smd_Dealer();
            if (!string.IsNullOrEmpty(subdealercode.Text))
            {
                subdealer = DealerService.GetByCode(subdealercode.Text);
            }

            #endregion

            if (store == null)
            {
                store = new t_StoreMasterData();
                store.AuthID = tb_authid_new.Text;
                store.IsEapprove = false;
            }
            store.DealerName = uc_dealer1.name;
            store.DealerCode = uc_dealer1.code;
            store.Status = ddl_storeStatus.SelectedValue;
            store.StoreType = store_type.SelectedValue;
            store.Channel = ddl_channel.Text;
            store.AreaName = AksRequest.GetString("tb_region").Trim();
            store.ProvinceName = AksRequest.GetString("tb_province").Trim();
            store.CityName = AksRequest.GetString("ddl_cityName").Trim();
            store.MallShortName = tb_MallShortName.Text;
            store.MallName = tb_MallName.Text;
            store.HouseNumber = tb_HouseNumber.Text;
            store.StoreName = AksRequest.GetString("tb_store_name");
            store.ShopSeq = ddl_ShopSeq.SelectedValue;
            store.ContractPerson = tb_ContractPerson.Text;
            store.Telephone = tb_Telephone.Text;
            store.Address = AksRequest.GetString("tb_address");
            store.DisplayArea = Utils.StrToDecimal(tb_size.Text, 0);
            store.OpenDate = Utils.StrToDateTimeN(tb_FirstStartDate.Text);
            store.IsColourService = cb_IsColourService.Checked;
            store.IsTintingService = cb_IsTintingService.Checked;
            store.ShowInWebsite = cb_ShowInWebsite.Checked;
            store.CurrentStartDate = Utils.StrToDateTimeN(tb_CurrentStartDate.Text);

            #region Add By Tony 20160524
            store.OwnerType = (cb_ownertype.Checked) ? 2 : 1;
            store.SubDealerCode = subdealer.DealerCode == null ? "" : subdealer.DealerCode;
            store.SubDealerName = subdealer.Name == null ? "" : subdealer.Name;
            store.BMCCode = bmc.BMCCode == null ? "" : bmc.BMCCode;
            store.BMCName = bmc.BMCName == null ? "" : bmc.BMCName;
            store.AccountOwner = accountOwner.WindowsId == null ? "" : accountOwner.WindowsId;
            store.WechatId = tb_wechatid.Text;
            store.District = tb_District.Text;
            #endregion

            //store.NewFitment = ddl_NewFitment.SelectedValue;
            //store.ApplicationType = ddl_ApplactionType.SelectedValue;
            if (cb_IsUpgraded.Checked)
            {
                store.isUpgraded = true;
                store.BeforeUpgradedType = ddl_BeforeUpgradedType.SelectedValue;
            }
            if (cb_IsDowngraded.Checked)
            {
                store.IsDowngraded = true;
                store.BeforeDowngradedType = ddl_BeforeDowngradedType.SelectedValue;
            }
            if (cb_IsRenew.Checked)
            {
                store.IsRenew = true;
                store.BeforeRenewType = ddl_BeforeRenewType.SelectedValue;
                store.LastRenewDate = Utils.StrToDateTimeN(tb_LastRenewDate.Text);
            }
            store.StoreApprovedDate = Utils.StrToDateTimeN(tb_StoreApprovedDate.Text);
            store.EapproveSN = tb_EapproveSN.Text;


            store.SubmitDate = DateTime.Now;
            store.Creator = TaskAPI.UserName;

            // 如果流程编号已存在，重新生成
            if ((t_StoreMasterData._ApplicationNO == applicationNo).Count<t_StoreMasterData>() > 0)
            {
                applicationNo = GenerateApplicationNo();
            }
            store.ApplicationNO = applicationNo;

            // 设备
            if (cb_isDevice.Checked)
            {
                store.DeviceFullSetSN = tb_FullSetSN.Text;
                store.DeviceStatus = ddl_Status.SelectedValue;
                store.DispenseModel = ddl_dispenseModel.SelectedValue;
                store.ShakerModel = ddl_shakerModel.SelectedValue;
                store.PcModel = ddl_PcModel.SelectedValue;
                store.DeviceEapproveSN = tb_DeviceEapproveSN.Text;
                store.DeviceApprovedDate = Utils.StrToDateTimeN(tb_DeviceStoreApprovedDate.Text);
                store.DevicePurchasedDate = Utils.StrToDateTimeN(tb_DevicePurchasedDate.Text);

                #region Add By Tony 20160524
                if (cb_istransfermachine.Checked)
                {
                    store.IsTransferMachine = true;
                }

                store.CustomerDevice = l_customerdevice.Text;
                #endregion

            }

            store.Process = TaskAPI.Process;
            store.Incident = TaskAPI.Incident;
            store.TaskId = TaskAPI.TaskID;


            return store;
        }
        #endregion

        #region 显示只读数据、隐藏编辑控件

        private void ShowData(t_StoreMasterData store)
        {
            l_authid_new.Text = store.AuthID;
            l_storeStatus.Text = store.Status;
            l_store_type.Text = StoreService.GetStoreType(store.StoreType);
            l_channel.Text = store.Channel;
            l_region.Text = store.AreaName;
            l_province.Text = store.ProvinceName;
            l_cityName.Text = store.CityName;
            l_MallShortName.Text = store.MallShortName;
            l_MallName.Text = store.MallName;
            l_HouseNumber.Text = store.HouseNumber;
            l_store_name.Text = store.StoreName;
            l_ShopSeq.Text = store.ShopSeq;
            l_ContractPerson.Text = store.ContractPerson;
            l_Telephone.Text = store.Telephone;
            l_address.Text = store.Address;
            l_size.Text = store.DisplayArea == null ? "0" : store.DisplayArea.Value.ToString();
            l_FirstStartDate.Text = store.OpenDate == null ? "" : store.OpenDate.Value.ToString("yyyy-MM");
            l_IsColourService.Text = store.IsColourService == null ? "否" : (store.IsColourService.Value ? "是" : "否");
            l_IsTintingService.Text = store.IsTintingService == null ? "否" : (store.IsTintingService.Value ? "是" : "否");
            l_ShowInWebsite.Text = store.ShowInWebsite == null ? "否" : (store.ShowInWebsite.Value ? "是" : "否");
            l_CurrentStartDate.Text = store.CurrentStartDate == null ? "" : store.CurrentStartDate.Value.ToString("yyyy-MM");
            l_LastRenewDate.Text = store.LastRenewDate == null ? "" : store.LastRenewDate.Value.ToString("yyyy-MM");
            l_ApplactionType.Text = store.ApplicationType;
            l_NewFitment.Text = store.NewFitment;
            l_istransfermachine.Text = store.IsTransferMachine == null ? "否" : (store.IsTransferMachine ? "是" : "否");
            #region Add By Tony 20160524

            if (!string.IsNullOrEmpty(store.SubDealerCode))
            {
                cb_ownertype.Checked = true;
                l_subdealercode.Text = store.SubDealerCode == null ? "" : store.SubDealerCode;
                l_subdealername.Text = store.SubDealerName == null ? "" : store.SubDealerName;
            }
            else
            {
                cb_ownertype.Checked = false;
                l_subdealercode.Text = "";
                l_subdealername.Text = "";
            }

            if (!string.IsNullOrEmpty(store.BMCCode))
            {
                l_bmccode.Text = store.BMCCode == null ? "" : store.BMCCode;
                l_bmcname.Text = store.BMCName == null ? "" : store.BMCName;
            }
            else
            {
                l_bmccode.Text = "";
                l_bmcname.Text = "";
            }

            //l_accountowner.Text = AccountOwnerService.GetById(store.AccountOwner == null ? "" : store.AccountOwner).AccountOwner;
            tb_accountowner.Visible = false;
            l_wechatid.Text = store.WechatId == null ? "" : store.WechatId;
            l_District.Text = store.District == null ? "" : store.District;
            l_customerdevice.Text = store.CustomerDevice == null ? "" : store.CustomerDevice;
            cb_istransfermachine.Checked = store.IsTransferMachine;
            #endregion



            if (store.isUpgraded == true)
            {
                l_IsUpgraded.Text = @"是";
                l_BeforeUpgradedType.Text = StoreService.GetStoreType(store.BeforeUpgradedType);
            }
            else
            {
                l_IsUpgraded.Text = @"否";
            }
            if (store.IsDowngraded == true)
            {
                l_IsDowngraded.Text = @"是";
                l_BeforeDowngradedType.Text = StoreService.GetStoreType(store.BeforeDowngradedType);
            }
            else
            {
                l_IsDowngraded.Text = @"否";
            }
            if (store.IsRenew == true)
            {
                l_IsRenew.Text = @"是";
                l_BeforeRenewType.Text = StoreService.GetStoreType(store.BeforeRenewType);
            }
            else
            {
                l_IsRenew.Text = @"否";
            }

            l_StoreApprovedDate.Text = store.StoreApprovedDate == null ? "" : store.StoreApprovedDate.Value.ToString("yyyy-MM");
            l_EapproveSN.Text = store.EapproveSN;

            // 设备
            if (StoreMasterDataService.IsExistDevice(store))
            {
                l_isDevice.Text = @"是";
                l_FullSetSN.Text = store.DeviceFullSetSN;
                l_Status.Text = store.DeviceStatus;
                l_MachineDeposit.Text = store.MachineDeposit == null ? "" : store.MachineDeposit.Value.ToString("N");
                l_dispenseModel.Text = store.DispenseModel;
                l_shakerModel.Text = store.ShakerModel;
                l_PcModel.Text = store.PcModel;
                l_DeviceStoreApprovedDate.Text = store.DeviceApprovedDate == null ? "" : store.DeviceApprovedDate.Value.ToString("yyyy-MM");
                l_DeviceEapproveSN.Text = store.DeviceEapproveSN;
                l_DevicePurchasedDate.Text = store.DevicePurchasedDate == null ? "" : store.DevicePurchasedDate.Value.ToString("yyyy-MM");
            }
            else
            {
                tbody_device.Visible = false;
            }

            hideController();
        }

        private void hideController()
        {
            #region 隐藏控件

            ddl_ShopSeq.Visible = false;
            cb_isDevice.Visible = false;

            var parentControls = new List<System.Web.UI.HtmlControls.HtmlGenericControl>();
            parentControls.Add(tbody_store);
            parentControls.Add(tbody_other);
            parentControls.Add(tbody_history);
            parentControls.Add(tbody_device);
            foreach (var parent in parentControls)
            {
                foreach (var control in parent.Controls)
                {
                    if (control is TextBox)
                    {
                        var tb = control as TextBox;
                        tb.Visible = false;
                    }
                    else if (control is DropDownList)
                    {
                        var ddl = control as DropDownList;
                        ddl.Visible = false;
                    }
                    else if (control is CheckBox)
                    {
                        var ck = control as CheckBox;
                        ck.Visible = false;
                    }
                }
            }

            filterStore.Visible = false;
            #endregion
        }

        private void ShowEdit(t_StoreMasterData store)
        {
            var dt = DbHelperSQL.Query(
                "select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" +
                store.ProvinceName +
                "' and [level] = 2) order by seq asc").Tables[0];
            ddl_cityName.Items.Clear();
            ddl_cityName.AppendDataBoundItems = true;
            ddl_cityName.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt.Rows)
            {
                ddl_cityName.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            tb_store_name.ReadOnly = false;
            tb_address.ReadOnly = false;

            tb_authid_new.ReadOnly = true;

            hd_store_id.Value = store.ID.ToString();
            ddl_storeStatus.SelectedValue = store.Status;
            store_type.SelectedValue = StoreService.GetStoreTypeCode(store.StoreType);
            ddl_channel.SelectedValue = store.Channel;
            tb_region.Text = store.AreaName;
            tb_province.Text = store.ProvinceName;
            ddl_cityName.SelectedValue = store.CityName;
            tb_MallShortName.Text = store.MallShortName;
            tb_MallName.Text = store.MallName;
            tb_HouseNumber.Text = store.HouseNumber;
            tb_store_name.Text = store.StoreName;
            ddl_ShopSeq.SelectedValue = store.ShopSeq;
            tb_ContractPerson.Text = store.ContractPerson;
            tb_Telephone.Text = store.Telephone;
            tb_address.Text = store.Address;
            tb_size.Text = store.DisplayArea == null ? "" : store.DisplayArea.Value.ToString();
            tb_FirstStartDate.Text = store.OpenDate == null ? "" : store.OpenDate.Value.ToString("yyyy-MM");
            cb_IsColourService.Checked = store.IsColourService == true;
            cb_IsTintingService.Checked = store.IsTintingService == true;
            cb_ShowInWebsite.Checked = store.ShowInWebsite == true;
            tb_CurrentStartDate.Text = store.CurrentStartDate == null ? "" : store.CurrentStartDate.Value.ToString("yyyy-MM");
            tb_LastRenewDate.Text = store.LastRenewDate == null ? "" : store.LastRenewDate.Value.ToString("yyyy-MM");
            //#region Add By Tony 20160606
            //subdealercode.Text = store.SubDealerCode == null ? "" : store.SubDealerCode;
            //#endregion


            if (store.isUpgraded == true)
            {
                cb_IsUpgraded.Checked = true;
                ddl_BeforeUpgradedType.SelectedValue = StoreService.GetStoreTypeCode(store.BeforeUpgradedType);
            }
            if (store.IsDowngraded == true)
            {
                cb_IsDowngraded.Checked = true;
                ddl_BeforeDowngradedType.SelectedValue = StoreService.GetStoreTypeCode(store.BeforeDowngradedType);
            }
            if (store.IsRenew == true)
            {
                cb_IsRenew.Checked = true;
                ddl_BeforeRenewType.SelectedValue = StoreService.GetStoreTypeCode(store.BeforeRenewType);
            }

            tb_StoreApprovedDate.Text = store.StoreApprovedDate == null ? "" : store.StoreApprovedDate.Value.ToString("yyyy-MM");
            tb_EapproveSN.Text = store.EapproveSN;

            // 设备
            if (StoreMasterDataService.IsExistDevice(store))
            {
                cb_isDevice.Checked = true;
                tb_FullSetSN.Text = store.DeviceFullSetSN;
                ddl_Status.SelectedValue = store.DeviceStatus;
                l_MachineDeposit.Text = store.MachineDeposit == null ? "" : store.MachineDeposit.Value.ToString("N");
                ddl_dispenseModel.SelectedValue = store.DispenseModel;
                ddl_shakerModel.SelectedValue = store.ShakerModel;
                ddl_PcModel.SelectedValue = store.PcModel;
                tb_DeviceEapproveSN.Text = store.DeviceEapproveSN;
                tb_DeviceStoreApprovedDate.Text = store.DeviceApprovedDate == null ? "" : store.DeviceApprovedDate.Value.ToString("yyyy-MM");
                tb_DevicePurchasedDate.Text = store.DevicePurchasedDate == null ? "" : store.DevicePurchasedDate.Value.ToString("yyyy-MM");
            }
            else
            {
                tbody_device.Visible = false;
            }
        }

        #endregion

        #region 履约保证金
        public void Margin(t_StoreMasterData store, t_smd_Store smdStore)
        {
            var taskApi = new TaskAPI(TaskHelper.STORE_DEPOSIT_RECEIVE_TASKID);
            var applicationNo = GenerateApplicationNo(taskApi);
            taskApi["IsRenovation"] = "1";
            taskApi["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue");
            taskApi["ParentProcess"] = TaskAPI.Process;
            taskApi["ParentIncident"] = TaskAPI.Incident;
            taskApi["AutoBusinessKey"] = Constant.PROCESS_STORE;
            taskApi.InitAutoTask(applicationNo);
            taskApi["StoreName"] = smdStore.StoreName;

            taskApi["IsCancel"] = "0";
            taskApi["IsDevice"] = "0";
            taskApi.Summary = "履约保证金确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + uc_dealer1.code + "|" + store.AuthID;

            var channels = store.Channel == "多乐士" ? "DULUX" : "LEVIS";
            taskApi["DealerID"] = uc_dealer1.dealer.DealerCode;
            taskApi["AuthID"] = store.AuthID;
            taskApi["StoreType"] = (store.NewFitment == "从IS升级" ? "DCSS" : store.StoreType);
            taskApi["Channel"] = channels;

            taskApi.SetDepositReceiveRecipient(store.AreaName, store.ProvinceName, channels.ToUpper());

            if (taskApi.Send())
            {
                var ass = taskApi.InitAutoAssessment();
                Storage.Save(Storage.Context1, ass);

                // 添加业务主数据
                var _storeMasterData = new t_StoreMasterData();
                _storeMasterData.SubmitDate = DateTime.Now;
                _storeMasterData.Creator = taskApi.UserName;
                _storeMasterData.ApplicationNO = taskApi.ApplicationNo;
                _storeMasterData.Process = taskApi.Process;
                _storeMasterData.Incident = taskApi.Incident;
                _storeMasterData.StoreId = Utils.StrToInt(TaskAPI.GetVariableBySingleValue("BlankVlue"), 0);
                _storeMasterData.BuyMachineDeposit = store.BuyMachineDeposit;
                _storeMasterData.DispenseModel = store.DispenseModel;
                _storeMasterData.ShakerModel = store.ShakerModel;
                _storeMasterData.PcModel = store.PcModel;
                _storeMasterData.MachineDeposit = store.MachineDeposit;
                _storeMasterData.IsEapprove = store.IsEapprove;
                _storeMasterData.NewFitment = store.NewFitment;
                _storeMasterData.ApplicationType = store.ApplicationType;
                _storeMasterData.BusinessKey = ass.BusinessKey;
                _storeMasterData.BusinessProcess = ass.BusinessProcess;
                _storeMasterData.DeviceApprovedDate = store.StoreApprovedDate;

                Storage.Save(Storage.Context1, _storeMasterData);
                BusinessService.SaveChildProcess(taskApi, ass, "active");
            }
        }
        #endregion

    }
}